#include "clib_config.h"
#include "clib_backtrace.h"
#include <stdio.h>
#include "clib_spinlock.h"
#include <pthread.h>
#include <unistd.h>
#include "clib_rwlock.h"
#include "clib_log.h"

clib_spinlock_t lock;
clib_rwlock_t rw;
int   sum = 0;
pthread_mutex_t mu;
void* thread_function(void* arg)
{
    for(int i = 0; i < 1000000; i++) {
        clib_spinlock_lock(&lock);
        //pthread_mutex_lock(&mu);
        sum++;
        clib_log_write(1,clib_log_debug,"log: %d\n",sum);
        clib_spinlock_unlock(&lock);
        //pthread_mutex_unlock(&mu);
    }
    //printf("====%d====\n",sum);
    //pthread_exit(NULL);
}
void* thread_function_rw(void* arg)
{
    for(int i = 0; i < 100000; i++) {
        clib_rwlock_write_lock(&rw);
        //pthread_mutex_lock(&mu);
        sum++;
        clib_log_write(1,clib_log_debug,"log: %d\n",sum);
        clib_rwlock_write_unlock(&rw);
        //pthread_mutex_unlock(&mu);
    }
    //printf("====%d====\n",sum);
    //pthread_exit(NULL);
}
void* thread_function_rd(void* arg)
{
    for(int i = 0; i < 10; i++) {
        clib_rwlock_read_lock(&rw);
        //pthread_mutex_lock(&mu);
        printf("===%d====\n",sum);
        
        clib_rwlock_read_unlock(&rw);
        sleep(1);
        //pthread_mutex_unlock(&mu);
    }
    //printf("====%d====\n",sum);
    //pthread_exit(NULL);
}
#define NUM_THREADS 4

int main(void) 
{
    clib_spinlock_init(&lock);
    pthread_mutex_init(&mu, NULL);
    clib_rwlock_init(&rw);
    pthread_t threads[NUM_THREADS];
    int thread_args[NUM_THREADS];
    int i;
    clib_log_init("test.log",1,clib_log_info);
    // 创建线程
    for (i = 0; i < NUM_THREADS; i++) {
        thread_args[i] = i;
        if (pthread_create(&threads[i], NULL, thread_function_rw, 0) != 0) {
            fprintf(stderr, "Error creating thread\n");
            return 0;
        }
    }

    // 创建线程
    for (i = 0; i < 2; i++) {
        thread_args[i] = i;
        if (pthread_create(&threads[i], NULL, thread_function_rd, 0) != 0) {
            fprintf(stderr, "Error creating thread\n");
            return 0;
        }
    }
    
    //thread_function(NULL);
    
    // 等待线程结束
    for (i = 0; i < NUM_THREADS; i++) {
        if (pthread_join(threads[i], NULL) != 0) {
            fprintf(stderr, "Error joining thread\n");
            return 0;
        }
    }
    printf("====%d====\n",sum);
    return 0;

}